# // 以下提供一个简单的方式快速部署一个https服务器，用于非生产环境的测试使用，如果是正式的生产环境，考虑到性能安全等因素，就不要使用这个了。
# 1、使用 pyOpenSSL 库：# coding:utf-8
import time
from http.server import HTTPServer, BaseHTTPRequestHandler
from http.server import SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn
from socketserver import BaseServer
from OpenSSL import SSL
# 2、使用自带ssl库(python 2.6之后)：# coding:utf-8
import os
import ssl
import socket


# 类定义
class People:
    # 定义基本属性
    name = ''
    age = 0
    # 定义私有属性,私有属性在类外部无法直接进行访问
    __weight = 0

    # 定义构造方法
    def __init__(self, n, a, w):
        self.name = n
        self.age = a
        self.__weight = w

    def speak(self):
        print("%s 说: 我身份是 People,今年 %d 岁。" % (self.name, self.age))


# 单继承示例
class Student(People):
    grade = ''

    def __init__(self, n, a, w, g):
        # 调用父类的构函
        People.__init__(self, n, a, w)
        self.grade = g

    # 覆写父类的方法
    def speak(self):
        print("%s 说: 我身份是 Student,今年 %d 岁了，我在读 %d 年级" % (self.name, self.age, self.grade))


# 另一个类，多重继承之前的准备
class Speaker:
    topic = ''
    name = ''

    def __init__(self, n, t):
        self.name = n
        self.topic = t

    def speak(self):
        print("我叫 %s，我是一个演说家，我演讲的主题是 %s" % (self.name, self.topic))


# 多重继承
class Sample(Speaker, Student):
    a = 26

    def __init__(self, n, a, w, g, t):
        Student.__init__(self, n, a, w, g)
        Speaker.__init__(self, n, t)

    def __call__(self, *args, **kwargs):
        print("我叫 %s，虚度 %d 岁" % (self.name, self.age,))

    def speak(self):
        print("我叫 %s，我是一个Sample" % (self.name,))


class Parent:  # 定义父类

    def __init__(self, *args, directory=None, **kwargs):
        if directory is None:  # 注意这里没有判断 self.directory is not None
            directory = os.getcwd()
        self.directory = directory

    def myMethod(self):
        print('{}调用父类方法:directory={}'.format(self, self.directory))


class Child(Parent):  # 定义子类
    def __init__(self, *args, directory=None, **kwargs):
        if directory is None:
            directory = "\\".join(os.getcwd().split(sep="\\")[:-1] + ["snapshot"])
        self.directory = directory
        print("======" * 5)
        print("调用父类构造方法前 self.directory: {}".format(self.directory))
        # super(Child, self).__init__(*args, directory=directory, **kwargs)
        super(Child, self).__init__(*args, **kwargs)
        print("调用父类构造方法后 self.directory: {}".format(self.directory))

    def myMethod(self, directory=None):
        print('{}调用子类方法:directory={}'.format(self, self.directory))


def main_openssl():
    print("Start web server ...")
    webServerPort = 31000
    httpserver = ThreadedHTTPServer(("", webServerPort), WelcomeHandler)
    try:
        httpserver.serve_forever()
    except(KeyboardInterrupt, ):
        print("\nStop web server ...")


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    def __init__(self, server_address, handlerclass):
        BaseServer.__init__(self, server_address, handlerclass)
        ctx = SSL.Context(SSL.SSLv23_METHOD)
        ctx.use_privatekey_file("www.google.com.key")
        ctx.use_certificate_file("www.google.com.crt")
        self.socket = SSL.Connection(ctx, socket.socket(self.address_family, self.socket_type))
        self.socket.setblocking(0)
        self.server_bind()
        self.server_activate()

    def finish_request(self, request, client_address):
        try:
            self.RequestHandlerClass(request, client_address, self)
        except SSL.ZeroReturnError:
            print("SSL.ZeroReturnError")


class WelcomeHandler(BaseHTTPRequestHandler):
    def setup(self):
        self.connection = self.request

        self.rfile = self.connection.makefile(self.request, "rb", self.rbufsize)
        self.wfile = self.connection.makefile(self.request, "wb", self.wbufsize)

    def response(self, code, htmlpage):
        self.send_response(code)
        self.send_header("Content-type","text/html")
        self.end_headers()
        self.wfile.write(htmlpage)

    def do_GET(self):
        if self.path == "/hello":
            self.response(200, "Hello World.\n".encode("utf-8"))
            return
        self.response(200, "GET request.\n".encode("utf-8"))

    def do_POST(self):
        self.response(200, "POST request.\n".encode("utf-8"))

    def do_PUT(self):
        self.response(200,"PUT request.\n".encode("utf-8"))


def main_ssl():
    httpd = ThreadedHTTPSServer(('0.0.0.0', 443), MyWelcomeHandler)
    httpd.socket = ssl.wrap_socket(httpd.socket,
                                   certfile='www.google.com.crt',
                                   keyfile="www.google.com.key",
                                   server_side=True)
    try:
        httpd.serve_forever()
    except (KeyboardInterrupt,):
        print("\nStop web server ...")


class ThreadedHTTPSServer(ThreadingMixIn, HTTPServer):
    """ this is a example https server"""


class MyWelcomeHandler(SimpleHTTPRequestHandler):
    def __init__(self, *args, directory=None, **kwargs):
        if directory is None:
            directory = "\\".join(os.getcwd().split(sep="\\")[:-1] + ["snapshot"])
            print("======" * 5)
            print("Current Working Directory: {}".format(directory))
        self.directory = directory
        super(MyWelcomeHandler, self).__init__(*args, directory=directory, **kwargs)

    def response(self, code, htmlpage: bytes):
        self.send_response(code)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(htmlpage)

    def do_GET(self):
        page = "This is a GET request"
        if self.path.startswith("/search"):
            page = """
            <html>

            <script>
            function GetRequest() {
                var url = location.search; //获取url中"?"符后的字串
                var theRequest = new Object();
                if (url.indexOf("?") != -1) {
                    var str = url.substr(1);
                    strs = str.split("&");
                    for(var i = 0; i < strs.length; i ++) {
                        theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
                    }
                }
                return theRequest;
            } 

            // 调用Querystring
            var Request = new Object();
            Request = GetRequest();
            var name,age;
            name = Request['name'];
            age = Request['age'];
            m3u8_url = Request['url'];
            search_query_word = Request['q'];
            // document.write(search_query_word);
            window.location.href = "https://www.baidu.com/s?wd=" + search_query_word;
            // 跳转 window.location.href = "目标URL"; // 路由跳转到目标URL
            // HLS
            /*
              if(Hls.isSupported()) {
                var video = document.getElementById('myvideo'); // 获取 video 标签
                var hls = new Hls(); // 实例化 Hls 对象
                hls.loadSource(m3u8_url || 'index.m3u8.local'); // 传入路径
                hls.attachMedia(video);
                hls.on(Hls.Events.MANIFEST_PARSED,function() {
                  video.play(); // 调用播放 API
              });
             }
            */
            </script>
            </html>
                        """
            self.response(200, page.encode("utf-8"))
        elif self.path.startswith("/hello"):
            page = """
<html>

<script>
function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for(var i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]]=decodeURI(strs[i].split("=")[1]);
        }
    }
    return theRequest;
} 

// 调用Querystring
var Request = new Object();
Request = GetRequest();
var name,age;
name = Request['name'];
age = Request['age'];
m3u8_url = Request['url'];
search_query_word = Request['q'];
document.write(search_query_word);
// window.location.href = "https://www.baidu.com/s?wd=" + search_query_word;
// 跳转 window.location.href = "目标URL"; // 路由跳转到目标URL
// HLS
/*
  if(Hls.isSupported()) {
    var video = document.getElementById('myvideo'); // 获取 video 标签
    var hls = new Hls(); // 实例化 Hls 对象
    hls.loadSource(m3u8_url || 'index.m3u8.local'); // 传入路径
    hls.attachMedia(video);
    hls.on(Hls.Events.MANIFEST_PARSED,function() {
      video.play(); // 调用播放 API
  });
 }
*/
</script>
</html>
            """
            # self.response(200, "Hello World.\n".encode("utf-8"))
            self.response(200, page.encode("utf-8"))
        else:
            SimpleHTTPRequestHandler.do_GET(self)

    def do_POST(self):
        self.response(200, "This is a POST request.\n".encode("utf-8"))

    def do_PUT(self):
        self.response(200, "This is a PUT request.\n".encode("utf-8"))


if __name__ == '__main__':
    main_ssl()
    exit(0)
    print(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.stat("..").st_ctime))=}')
    c = Child()  # 子类实例
    c.myMethod()  # 子类调用重写方法
    super(Child, c).myMethod()  # 用子类对象调用父类已被覆盖的方法
    Parent.myMethod(c)  # 用子类对象调用父类已被覆盖的方法
    peter = Sample("Tim", 25, 80, 4, "Python")  # Sample -> (Speaker 隐式继承---> Student) -> People
    print(f"${Sample.mro()=}")
    peter.speak()  # 方法名同，默认调用的是在括号中参数位置排前父类的方法
    Student.speak(peter)
    print(f"{peter()=}")
    print(peter)
    print(object())
    super(Sample, peter).speak()
    super(Speaker, peter).speak()
    super(Student, peter).speak()

